<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="计划编号" prop="planCode">
        <el-input
          v-model="queryParams.planCode"
          placeholder="请输入计划编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="BOM" prop="bomId">
        <el-select
          v-model="queryParams.bomId"
          placeholder="请选择BOM"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in bomOptions"
            :key="item.bomId"
            :label="item.bomName"
            :value="item.bomId"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="产品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入产品ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- 产品名称下拉框 -->
      <el-form-item label="产品" prop="productId">
        <el-select
          v-model="queryParams.productId"
          placeholder="请选择产品"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in productOptions"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划生产数量" prop="planQuantity">
        <el-input
          v-model="queryParams.planQuantity"
          placeholder="请输入计划生产数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="实际生产数量" prop="actualQuantity">
        <el-input
          v-model="queryParams.actualQuantity"
          placeholder="请输入实际生产数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="生产线ID" prop="lineId">
        <el-input
          v-model="queryParams.lineId"
          placeholder="请输入生产线ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- 生产线名称下拉框 -->
      <el-form-item label="生产线" prop="lineId">
          <el-select
            v-model="queryParams.lineId"
            placeholder="请选择生产线"
            clearable
            @keyup.enter="handleQuery"
          >
            <el-option
              v-for="item in lineOptions"
              :key="item.lineId"
              :label="item.lineName"
              :value="item.lineId"
            />
          </el-select>
        </el-form-item>
      <el-form-item label="计划开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择计划开始时间">
          
        </el-date-picker>
      </el-form-item>
      <el-form-item label="计划结束时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择计划结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="计划状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择计划状态" clearable>
          <el-option
            v-for="dict in plan_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
          <el-option
            v-for="dict in plan_priority"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item> 
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pm:plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pm:plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pm:plan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pm:plan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="计划ID" align="center" prop="planId" /> -->
      <el-table-column label="计划编号" align="center" prop="planCode" />
      <el-table-column label="计划名称" align="center" prop="planName" />
      <el-table-column label="BOM" align="center" prop="bomName" />
      <!-- <el-table-column label="产品ID" align="center" prop="productId" /> -->
      <!-- 产品名称 -->
      <el-table-column label="产品" align="center" prop="productName" />
      <el-table-column label="计划生产数量" align="center" prop="planQuantity" />
      <!-- 不要了 -->
      <!-- <el-table-column label="实际生产数量" align="center" prop="actualQuantity" /> -->
      <!-- <el-table-column label="生产线ID" align="center" prop="lineId" /> -->
      <!-- 生产线名称 -->
      <el-table-column label="生产线" align="center" prop="lineName" />
      <el-table-column label="计划开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="plan_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority">
        <template #default="scope">
          <dict-tag :options="plan_priority" :value="scope.row.priority"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['pm:plan:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pm:plan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加BOM选择器组件 -->
    <BomSelector
      ref="bomSelectorRef"
      v-model:visible="bomSelectorVisible"
      @select="handleBomSelected"
    />

    <!-- 添加或修改生产计划对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="planRef" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划编号" prop="planCode">
              <el-input v-model="form.planCode" placeholder="请输入计划编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="BOM" prop="bomId" required>
              <div class="bom-selector-container">
                <el-input 
                  v-model="bomName" 
                  placeholder="请选择BOM" 
                  readonly 
                  class="bom-input"
                >
                  <template #append>
                    <el-button @click="openBomSelector">选择</el-button>
                  </template>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select 
                v-model="form.productId" 
                placeholder="请选择产品" 
                disabled 
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.productId"
                  :label="item.productName"
                  :value="item.productId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="计划生产数量" prop="planQuantity">
              <el-input-number v-model="form.planQuantity" :min="1" controls-position="right" placeholder="请输入计划生产数量" style="width: 200px;" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="生产线" prop="lineId">
              <el-select v-model="form.lineId" placeholder="请选择生产线">
                <el-option
                  v-for="item in lineOptions"
                  :key="item.lineId"
                  :label="item.lineName"
                  :value="item.lineId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择计划开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="计划结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择计划结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="计划状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择计划状态">
                <el-option
                  v-for="dict in plan_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级">
                <el-option
                  v-for="dict in plan_priority"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 所需物料明细展示 -->
        <div v-if="bomMaterials.length > 0" class="materials-container">
          <el-divider content-position="center">所需物料清单</el-divider>
          <el-table 
            :data="bomMaterials" 
            border 
            :header-cell-style="{background:'#f7f7f7'}"
            max-height="300px"
          >
            <el-table-column label="序号" type="index" width="50" align="center" />
            <el-table-column label="物料编码" prop="materialCode" width="120" align="center" />
            <el-table-column label="物料名称" prop="materialName" width="150" align="center" />
            <el-table-column label="规格型号" prop="specification" width="120" align="center" />
            <el-table-column label="单位用量" prop="quantity" width="80" align="center" />
            <el-table-column label="所需数量" width="100" align="center">
              <template #default="scope">
                <span>{{ calculateNeededQuantity(scope.row.quantity) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单位" prop="unit" width="80" align="center" />
            <el-table-column label="关键物料" prop="isKeyMaterial" width="80" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.isKeyMaterial === '1' ? 'danger' : 'info'">
                  {{ scope.row.isKeyMaterial === '1' ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Plan">
import { listPlan, getPlan, delPlan, addPlan, updatePlan, listProduct, listLine,listBom } from "@/api/pm/plan";
import { getBom } from "@/api/pm/bom";
import BomSelector from "@/components/BomSelector/index.vue";
import { generatePlanCode } from "@/utils/generator";

const { proxy } = getCurrentInstance();
const { plan_status, plan_priority } = proxy.useDict('plan_status', 'plan_priority');
const planList = ref([]);  // 
const productOptions = ref([]); // 产品下拉框选项
const lineOptions = ref([]); // 生产线下拉框选项
const bomOptions = ref([]); // BOM下拉框选项
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// BOM选择器相关变量
const bomSelectorVisible = ref(false);
const bomSelectorRef = ref(null);
const bomName = ref(''); // 用于显示已选BOM名称
const bomMaterials = ref([]); // 用于存储BOM物料清单

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planCode: null,
    planName: null,
    productId: null,
    planQuantity: null,
    actualQuantity: null,
    lineId: null,
    startTime: null,
    endTime: null,
    status: null,
    priority: null,
    bomId: null,
  },
  rules: {
    planCode: [
      { required: true, message: "计划编号不能为空", trigger: "blur" }
    ],
    planName: [
      { required: true, message: "计划名称不能为空", trigger: "blur" }
    ],
    productId: [
      { required: true, message: "产品ID不能为空", trigger: "blur" }
    ],
    planQuantity: [
      { required: true, message: "计划生产数量不能为空", trigger: "blur" }
    ],
    lineId: [
      { required: true, message: "生产线ID不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "计划开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "计划结束时间不能为空", trigger: "blur" }
    ],
    bomId: [
      { required: true, message: "请选择BOM", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询生产计划列表 */
function getList() {
  loading.value = true;
  listPlan(queryParams.value).then(response => {
    planList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    planId: null,
    planCode: null,
    planName: null,
    productId: null,
    planQuantity: null,
    actualQuantity: null,
    lineId: null,
    startTime: null,
    endTime: null,
    status: "0", // 修改默认值为"未开始"状态码
    priority: null,
    bomId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("planRef");
  // 清空BOM选择相关数据
  bomName.value = '';
  bomMaterials.value = [];
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.planId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.planCode = generatePlanCode();
  open.value = true;
  title.value = "添加生产计划";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _planId = row.planId || ids.value
  getPlan(_planId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改生产计划";
    
    // 获取BOM名称和物料明细 - 这里需要修改
    if (form.value.bomId) {
      getBom(form.value.bomId).then(async res => {
        if (res.data) {
          bomName.value = res.data.bomName;
          
          // 检查并完善物料明细信息
          if (res.data.bomDetailList && res.data.bomDetailList.length > 0) {
            // 处理可能缺失物料信息的情况
            try {
              // 使用Promise.all并行处理所有物料查询
              const detailsWithInfo = await Promise.all(
                res.data.bomDetailList.map(async detail => {
                  // 如果物料信息不完整，尝试获取完整信息
                  if (!detail.materialName || !detail.materialCode || !detail.specification) {
                    try {
                      // 导入物料API
                      const { getMaterial } = await import('@/api/mwm/material');
                      const materialRes = await getMaterial(detail.materialId);
                      if (materialRes.data) {
                        // 合并物料信息
                        return {
                          ...detail,
                          materialName: materialRes.data.materialName || detail.materialName,
                          materialCode: materialRes.data.materialCode || detail.materialCode,
                          specification: materialRes.data.specification || detail.specification,
                          unit: materialRes.data.unit || detail.unit
                        };
                      }
                    } catch (err) {
                      console.error("获取物料信息失败:", err);
                    }
                  }
                  return detail;
                })
              );
              bomMaterials.value = detailsWithInfo;
            } catch (err) {
              console.error("处理物料明细失败:", err);
              bomMaterials.value = res.data.bomDetailList || [];
            }
          } else {
            bomMaterials.value = [];
          }
        }
      });
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["planRef"].validate(valid => {
    if (valid) {
      // 检查BOM是否已选择
      if (!form.value.bomId) {
        proxy.$modal.msgError("请选择BOM");
        return;
      }
      // 检查产品是否已设置（应由BOM自动设置）
      if (!form.value.productId) {
        proxy.$modal.msgError("产品信息缺失，请重新选择BOM");
        return;
      }
      
      if (form.value.planId != null) {
        updatePlan(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPlan(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _planIds = row.planId || ids.value;
  proxy.$modal.confirm('是否确认删除生产计划编号为"' + _planIds + '"的数据项？').then(function() {
    return delPlan(_planIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('pm/plan/export', {
    ...queryParams.value
  }, `plan_${new Date().getTime()}.xlsx`)
}

// 在组件挂载时获取数据
onMounted(() => {
  // 获取产品列表
  listProduct().then(response => {
    productOptions.value = response.data; // 根据你的接口返回结构调整
  });
  // 获取生产线列表
  listLine().then(response => {
    lineOptions.value = response.data; // 根据你的接口返回结构调整
  });
  // 获取BOM列表
  listBom().then(response => {
    bomOptions.value = response.data; // 根据你的接口返回结构调整
  });
  getList(); // 原有的获取计划列表
});


// 打开BOM选择器
function openBomSelector() {
  bomSelectorRef.value.open();
}

// 处理BOM选择事件
function handleBomSelected(result) {
  if (result && result.bom) {
    // 设置BOM ID和名称
    form.value.bomId = result.bom.bomId;
    bomName.value = result.bom.bomName;
    
    // BOM选择后自动设置产品
    if (result.bom.productId) {
      form.value.productId = result.bom.productId;
      
      // 更新产品名称显示 - 如果需要显示产品名称
      const product = productOptions.value.find(p => p.productId === result.bom.productId);
      if (product) {
        // 这里可以设置产品名称的显示，如果需要的话
        console.log(`选择的产品: ${product.productName}`);
      }
    }
    
    // 保存BOM物料明细
    bomMaterials.value = result.details || [];
    
    proxy.$modal.msgSuccess(`已选择BOM: ${result.bom.bomName}`);
  }
}

// 计算所需物料数量
function calculateNeededQuantity(unitQuantity) {
  // 单位用量 * 计划生产数量
  if (!form.value.planQuantity || !unitQuantity) return 0;
  return (parseFloat(unitQuantity) * parseFloat(form.value.planQuantity)).toFixed(2);
}
</script>

<style scoped>
.bom-selector-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.bom-input {
  width: 100%;
}

.materials-container {
  margin-top: 15px;
}
</style>
